package com.sweets.look.ui.view;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.MailTo;
import android.net.http.SslError;
import android.os.Build;
import android.os.Message;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.webkit.ConsoleMessage;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.GeolocationPermissions;
import android.webkit.HttpAuthHandler;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.sweets.look.R;
import com.sweets.look.constant.Constants;
import com.sweets.look.preference.PreferenceManager;
import com.sweets.look.ui.activity.BrowserActivity;
import com.sweets.look.ui.browser.AdBlock;
import com.sweets.look.ui.browser.LightningDownloadListener;
import com.sweets.look.ui.widget.MarkDialog;
import com.sweets.look.ui.widget.MarkEditDialog;
import com.sweets.look.ui.widget.MarkEditDialog.OnCustomDialogListener;
import com.sweets.look.ui.widget.SwipeDismissTouchListener;
import com.sweets.look.ui.widget.SwipeDismissTouchListener.DismissCallbacks;
import com.sweets.look.ui.widget.supertoast.SuperActivityToast;
import com.sweets.look.util.BitmapUtils;
import com.sweets.look.util.BrowserUtils;
import com.sweets.look.util.IntentUtils;
import com.sweets.look.util.LogUtils;
import com.sweets.look.util.Utils;
import com.sweets.look.util.ViewUtils;

import java.io.ByteArrayInputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BrowserView {
    private final String TAG = BrowserView.class.getSimpleName();

    private class CustomGestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public void onLongPress(MotionEvent e) {
            mBrowserController.onLongPress();
        }
    }

    private class JsInteration {

        @JavascriptInterface
        public String getInfo(int what) {
            return mBrowserController.getInfo(what);
        }

        @JavascriptInterface
        public void getWebText(String text) {
            mBrowserController.getWebText(text);
        }

        @JavascriptInterface
        public void record(String url, String tag) {
            mBrowserController.recordAds(url, tag);
        }

        @JavascriptInterface
        public void searchText() {
            mBrowserController.searchText();
        }
    }


    /**
     * WebChromeClient主要用来辅助WebView处理Javascript的对话框、网站图标、网站标题以及网页加载进度等。
     */
    public class LightningChromeClient extends WebChromeClient {
        private Context mContext;

        public LightningChromeClient(Context context) {
            super();
            this.mContext = context;
        }

        @Override
        public Bitmap getDefaultVideoPoster() {
            return mBrowserController.getDefaultVideoPoster();
        }

        @Override
        public View getVideoLoadingProgressView() {
            return mBrowserController.getVideoLoadingProgressView();
        }

        @Override
        public void onCloseWindow(WebView window) {
            super.onCloseWindow(window);
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage cm) {
            LogUtils.w(TAG, cm.message() + " at " + cm.sourceId() + " : " + cm.lineNumber());
            return true;
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message
                resultMsg) {
            mBrowserController.onCreateWindow(isUserGesture, resultMsg);
            return isUserGesture;
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback
                callback) {

            Utils.requestPermission(this.mContext, new String[]{"android.permission.ACCESS_FINE_LOCATION"});
            MarkDialog dialog = new MarkDialog(mActivity).builder();
            dialog.setTitle(mActivity.getString(R.string.location));
            String v1 = origin.length() > 50 ? origin.subSequence(0, 50) + "..." : origin;
            dialog.setMessage(v1 + mActivity.getString(R.string.message_location))
                    .setCancelable(true)
                    .setPositiveButton(mActivity.getString(R.string.action_allow), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            callback.invoke(origin, true, true);
                        }
                    }).setNegativeButton(mActivity.getString(R.string.action_dont_allow), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callback.invoke(origin, false, true);
                }
            }).show();
        }

        @Override
        public void onHideCustomView() {
            mBrowserController.onHideCustomView();
            super.onHideCustomView();
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            new MarkDialog(mActivity).builder().setTitle(mActivity
                    .getResources().getString(R.string.dialog_message))
                    .setMessage(message)
                    .setCancelable(false)
                    .setPositiveButton(mActivity.getResources().getString(R.string.action_yes),
                            new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    result.confirm();
                                }
                            }).show();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            new MarkDialog(mActivity).builder().setTitle(mActivity
                    .getResources().getString(R.string.dialog_message))
                    .setMessage(message).setCancelable(false).
                    setPositiveButton(mActivity.getResources().getString(R.string.action_yes),
                            new View.OnClickListener() {
                                public void onClick(View v) {
                                    result.confirm();
                                }
                            }).setNegativeButton(mActivity.getResources().getString(R.string.action_no), new
                    View.OnClickListener() {
                        public void onClick(View v) {
                            result.cancel();
                        }
                    }).show();
            return true;
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult
                result) {
            new MarkEditDialog(mActivity).builder().setTitle(mActivity
                    .getResources().getString(R.string.dialog_message)).setCancelable(false).setTitleHint(message,
                    defaultValue).setPositiveButton(mActivity.getResources().getString(
                    R.string.action_ok), new OnCustomDialogListener() {
                public void back(String title, String msg, String other) {
                    result.confirm(title);
                }
            }).setNegativeButton(mActivity.getResources().getString(R.string.action_no), new
                    View.OnClickListener() {
                        public void onClick(View v) {
                            result.cancel();
                        }
                    }).show();
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if ((mBrowserFrame.isShown()) && nowId == view.getId()) {
                mBrowserController.updateProgress(newProgress);
            }

            if (newProgress < 30) {
                isJsLoaded = false;
            } else if (!isJsLoaded) {
                mBrowserController.blockAds(view);
                isJsLoaded = true;
            }
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
//            mTitle.setFavicon(icon);
            int topColor = ViewUtils.getViewTopColor(view);
            mWebViewList.get(nowId).setWebColor(topColor);
            if (mWebViewList.get(nowId).isShown()) {
                mBrowserController.updateColor(topColor);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (view.isShown()) {
                if (title == null) {
                    mBrowserController.updateUrlBox(view.getUrl(), BrowserView.this
                                    .mActivity.getString(R.string.untitled), false,
                            false);
                } else {
                    mBrowserController.updateUrlBox(view.getUrl(), title,
                            false, false);
                }
            }

            if (title != null) {
                mTitle.setTitle(title);
            } else {
                mTitle.setTitle(null);
            }

            mBrowserController.updateHistory(title, view.getUrl());
        }

        @SuppressLint(value = {"NewApi"})
        @Deprecated
        public void onShowCustomView(View view, int requestedOrientation,
                                     WebChromeClient.CustomViewCallback callback) {
            if (Constants.API >= 14 && Constants.API <= 18) {
                mBrowserController.onShowCustomView(view, requestedOrientation, callback);
                super.onShowCustomView(view, requestedOrientation, callback);
            }
        }

        @Override
        public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
            if (Constants.API >= 19) {
                mBrowserController.onShowCustomView(view, mBrowserController
                        .getActivity().getRequestedOrientation(), callback);
                super.onShowCustomView(view, callback);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback arg3, WebChromeClient.FileChooserParams
                fileChooserParams) {
            mBrowserController.showFileChooser(arg3, fileChooserParams);
            return true;
        }

        public void openFileChooser(ValueCallback callback) {
            mBrowserController.openFileChooser(callback);
        }

        public void openFileChooser(ValueCallback callback, String acceptType) {
            mBrowserController.openFileChooser(callback);
        }

        public void openFileChooser(ValueCallback callback, String acceptType, String capture) {
            mBrowserController.openFileChooser(callback);
        }
    }

    /**
     * 用于辅助WebView，处理各种通知、请求等事件
     */
    public class LightningWebClient extends WebViewClient {
        final Context mContext;
        private boolean mIsRunning;
        private float mZoomScale;

        public LightningWebClient(Context context) {
            super();
            this.mContext = context;
        }

        @Override
        public void onFormResubmission(WebView view, final Message dontResend, final Message resend) {
            new MarkDialog(mActivity).builder().setTitle(mActivity
                    .getString(R.string.title_form_resubmission))
                    .setMessage(mActivity.getString(R.string.message_form_resubmission))
                    .setCancelable(true).setPositiveButton(mActivity.getString(R.string.action_yes),
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            resend.sendToTarget();
                        }
                    }).setNegativeButton(mActivity.getString(R.string.action_no), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dontResend.sendToTarget();
                }
            }).show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (mPreferences.getHideUnderlineEnabled()) {
                view.loadUrl("javascript:var es=document.getElementsByTagName(\'a\');for(i in es){es[i].style.textDecoration=\'none\';}");
            }

            if (PreferenceManager.getInstance().getNightModeEnabled()) {
                view.loadUrl("javascript:var es=document.getElementsByTagName(\'body\');for(i in es){es[i].style.background=\'#261d3b\';}");
                view.loadUrl("javascript:var es=document.getElementsByTagName(\'div\');for(i in es){es[i].style.background=\'#261d3b\';}");
                view.loadUrl("javascript:var es=document.getElementsByTagName(\'head\');for(i in es){es[i].style.background=\'#261d3b\';}");
            }

            mBrowserController.blockAds(view);
            if (view.isShown()) {
                if (view.getTitle() == null || (view.getTitle().trim().isEmpty())) {
                    mBrowserController.updateUrlBox(view.getUrl(), BrowserView.this
                                    .mActivity.getString(R.string.untitled), false,
                            false);
                } else {
                    mBrowserController.updateUrlBox(view.getUrl(), view.getTitle(),
                            false, false);
                }

                view.invalidate();
            }

            if (view.getTitle() == null || (view.getTitle().trim().isEmpty())) {
                mTitle.setTitle(null);
            } else {
                mTitle.setTitle(view.getTitle());
            }

            if (view.getWidth() > 0 && view.getHeight() > 0) {
                Bitmap bitmap = BrowserUtils.captureAll(view, view.getWidth(), view.getHeight(),
                        false, Bitmap.Config.RGB_565);
                mTitle.setCoverImage(bitmap);
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            if (mBrowserFrame.isShown()) {
                mBrowserController.updateUrlBox(url, "loading", false,
                        true);
            }

//          mTitle.setFavicon(mWebpageBitmap);
            if (mWebViewList.get(nowId) != null) {
                mWebViewList.get(nowId).setWebColor(-1);
                if (!mWebViewList.get(nowId).isShown()) {

                } else {
                    mBrowserController.updateColor(-1);
                }
            }

            mBrowserController.update(url);
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, final HttpAuthHandler handler, String host, String
                realm) {
            new MarkEditDialog(mActivity).builder().setTitle(mActivity
                    .getString(R.string.title_sign_in))
                    .setCanceledOnTouchOutside(true).setTitleHint(BrowserView
                    .this.mActivity.getString(R.string.hint_username), "")
                    .setMsgHint(mActivity
                            .getString(R.string.hint_password), "")
                    .setPositiveButton(mActivity.getString(
                            R.string.title_sign_in), new OnCustomDialogListener() {
                        @Override
                        public void back(String title, String msg, String other) {
                            handler.proceed(title.trim(), msg.trim());
                        }
                    }).setNegativeButton(mActivity.getString(R.string.action_cancel),
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            handler.cancel();
                        }
                    }).show();
        }

        @Override
        public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
            if (error.getPrimaryError() == SslError.SSL_UNTRUSTED) {//3
                new MarkDialog(mActivity).builder().setTitle(mActivity
                        .getString(R.string.title_warning))
                        .setMessage(mActivity.getString(R.string.message_untrusted_certificate))
                        .setCancelable(true).setPositiveButton(mActivity.getString(
                        R.string.action_yes), new View.OnClickListener() {
                    public void onClick(View v) {
                        handler.proceed();
                    }
                }).setNegativeButton(mActivity.getString(R.string.action_no), new View.OnClickListener
                        () {
                    public void onClick(View v) {
                        handler.cancel();
                    }
                }).show();
            } else {
                handler.proceed();
            }
        }

        @Override
        public void onScaleChanged(final WebView view, float oldScale, final float newScale) {
            if (view.isShown()) {
                if (Build.VERSION.SDK_INT < 19) {
                    view.invalidate();
                    return;
                }

                if (!mPreferences.getTextReflowEnabled()) {
                    view.invalidate();
                    return;
                }

                if (this.mIsRunning) {
                    return;
                }

                if (Math.abs(this.mZoomScale - newScale) <= 0.01f) {
                    //不缩放
                } else {
                    this.mIsRunning = view.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mZoomScale = newScale;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                view.evaluateJavascript("javascript:document.getElementsByTagName(\'body\')[0].style.width=window.innerWidth+\'px\';",
                                        null);//专门用于异步调用JavaScript方法，并且能够得到一个回调结果。
                            }
                            mIsRunning = false;
                        }
                    }, 100);

                }
            }
        }

        @TargetApi(value = 21)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest
                request) {
            return mAdBlock.isAd(request.getUrl().toString()) ?
                    new WebResourceResponse("text/plain", "utf-8", new ByteArrayInputStream("".getBytes()))
                    : super.shouldInterceptRequest(view, request);

        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            return mAdBlock.isAd(url) ?
                    new WebResourceResponse("text/plain", "utf-8", new ByteArrayInputStream("".getBytes()))
                    : super.shouldInterceptRequest(view, url);
        }

        /**
         * @param view
         * @param url
         * @return
         */
        @Override
        @SuppressLint(value = {"NewApi"})
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            LogUtils.w(TAG, "should override url loading");
            if (!BrowserView.this.handleLink(url)) {
                if (!BrowserView.mPreferences.getQuickBackEnabled()) {
                    if (!super.shouldOverrideUrlLoading(view, url)) {
                        return false;
                    }
                } else if (!BrowserView.this.doDirect(url)) {
                    return false;
                }

                return true;
            }
            return true;
        }
    }

    public class Title {
        private final Drawable mCloseIcon;
        private final Context mContext;
        //      private final Bitmap mDefaultIcon;
        private final View mRootView;
        private final ImageView mCover;
        //      private Bitmap mFavicon;
        private final int mFaviconSize;
        private int mId;
        private String mTitle;
        private TextView mTitleView;


        @SuppressLint(value = {"InflateParams"})
        public Title(Context context) {
            super();
//            this.mDefaultIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_webpage);
//            this.mFavicon = this.mDefaultIcon;
            this.mTitle = mActivity.getString(R.string.action_new_tab);
            this.mContext = context;
            LayoutInflater inflater = LayoutInflater.from(context);
            this.mFaviconSize = ViewUtils.convertToDensityPixels(context, 20);
            this.mCloseIcon = context.getResources().getDrawable(R.drawable.windowtab_close);
            if (BrowserView.class.desiredAssertionStatus() && this.mCloseIcon == null) {
                throw new AssertionError();
            }
            if (mCloseIcon != null) {
                mCloseIcon.setBounds(0, 0, mFaviconSize, mFaviconSize);
            }

            this.mRootView = (View) inflater.inflate(R.layout.browser_title, null);
            this.mCover = (ImageView) mRootView.findViewById(R.id.cover);
            this.mTitleView = (TextView) mRootView.findViewById(R.id.desc);
            this.mTitleView.setText(this.mTitle);
//          BitmapDrawable bitmapDrawable = new BitmapDrawable(null, this.mFavicon);
//          bitmapDrawable.setBounds(0, 0, this.mFaviconSize, this.mFaviconSize);
            this.mTitleView.setCompoundDrawables(null, null, this.mCloseIcon, null);

            this.mTitleView.setOnTouchListener(new SwipeDismissTouchListener(this.mTitleView, null,
                    mFaviconSize * 2, new DismissCallbacks() {
                @Override
                public boolean canDismiss(Object token) {
                    return true;
                }

                @Override
                public void onClickLand() {
                    mBrowserController.deleteTab(mId);
                }

                @Override
                public void onDismiss(View view, Object token) {
                    mBrowserController.deleteTab(mId);
                }
            }));
            this.mTitleView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!isDestroyed()) {
                        mBrowserController.showSelectedTab(mId);
                    }
                }
            });
            this.mTitleView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    mBrowserController.copyTagLink(mId);
                    return true;
                }
            });
        }


        public void activateTab() {
            if (this.mTitleView != null) {
                this.mTitleView.setTypeface(Typeface.defaultFromStyle(1));
                ViewUtils.setTextActive(this.mContext, this.mTitleView, true);
            }
        }

        public void deactivateTab() {
            if (this.mTitleView != null) {
                this.mTitleView.setTypeface(Typeface.defaultFromStyle(0));
                ViewUtils.setTextActive(this.mContext, this.mTitleView, false);
            }
        }

//        public Bitmap getFavicon() {
//            return this.mFavicon;
//        }

        public int getId() {
            return this.mId;
        }

        public String getTitle() {
            return this.mTitle;
        }

        public View getRootView() {
            return this.mRootView;
        }


//        public void setFavicon(Bitmap favicon) {
//            this.mFavicon = favicon;
//            if (this.mFavicon == null) {
//                this.mFavicon = this.mDefaultIcon;
//            }
//
//            BitmapDrawable drawable = new BitmapDrawable(null, this.mFavicon);
//            drawable.setBounds(0, 0, this.mFaviconSize, this.mFaviconSize);
//            this.mTitleView.setCompoundDrawables(drawable, null, this.mCloseIcon, null);
//        }

        public void setId(int id) {
            this.mTitleView.setId(id);
            this.mId = id;
        }

        public void setTitle(String title) {
            int v1 = R.string.untitled;
            if (title == null) {
                title = mActivity.getString(v1);
            } else if (title.isEmpty()) {
                title = mActivity.getString(v1);
            }

            this.mTitle = title;
            this.mTitleView.setText(title);
        }


        public void setCoverImage(Bitmap bitmap) {
            this.mCover.setImageBitmap(bitmap);
        }

        public void onDestroy() {
            if (mCover != null) {
                BitmapUtils.recycleImageView(mCover);
            }
        }
    }

    private FrameLayout.LayoutParams fraLayoutParams;
    private boolean isDestroyed = false;
    private boolean isJsLoaded = false;
    private final Activity mActivity;
    private static AdBlock mAdBlock;
    private BrowserActivity mBrowserController;
    private FrameLayout mBrowserFrame;
    private Context mContext;
    private static String mDefaultUserAgent;
    private final GestureDetector mGestureDetector;
    private static String mHomepage;
    private int mIdGenerator;
    private List<Integer> mIdList = new ArrayList<Integer>();
    private IntentUtils mIntentUtils;
    private static final float[] mNegativeColorArray = new float[]{-1f, 0f, 0f, 0f, 255f, 0f, -1f, 0f, 0f, 255f,
            0f, 0f, -1f, 0f, 255f, 0f, 0f, 0f, 1f, 0f};
    private final Paint mPaint = new Paint();
    private static PreferenceManager mPreferences;
    private WebSettings mSettings;
    private final Title mTitle;
    private List<FastView> mWebViewList = new ArrayList<FastView>();
    private static Bitmap mWebpageBitmap;
    private int nowId;


    @SuppressLint(value = {"NewApi"})
    public BrowserView(Activity activity, String url) {
        super();
        this.mActivity = activity;
        mPreferences = PreferenceManager.getInstance();
        this.mBrowserFrame = new FrameLayout(activity);
        mAdBlock = AdBlock.getInstance();
        this.fraLayoutParams = new FrameLayout.LayoutParams(-1, -1);
        this.mTitle = new Title(activity);
        mWebpageBitmap = BitmapFactory.decodeResource(activity.getResources(), R.drawable.ic_webpage);
        this.mBrowserController = (BrowserActivity) activity;

        this.mIntentUtils = new IntentUtils(this.mBrowserController);
        this.mGestureDetector = new GestureDetector(activity, new CustomGestureListener());

        FastView fastView = new FastView(activity);
        fastView.setId(this.mIdGenerator);
        this.mIdList.add(this.mIdGenerator);
        this.nowId = this.mIdGenerator;
        LogUtils.w(TAG, "init browser view and set now id = " + String.valueOf("" + this.nowId));
        ++this.mIdGenerator;
        this.mWebViewList.add(fastView);
        this.initializeWebView(activity, fastView);
        this.mBrowserFrame.addView(fastView, this.fraLayoutParams);

        if (url != null) {
            if (url.trim().isEmpty()) {
                return;
            }

            fastView.loadUrl(url);
            return;
        }

        if (mHomepage.startsWith("about:home")) {
            this.mBrowserController.openDefaultHomepage(fastView);
            return;
        }

        if (mHomepage.startsWith("about:links")) {
            this.mBrowserController.openDefaultHomepage(fastView);
            return;
        }

        if (mHomepage.startsWith("about:bookmarks")) {
            mBrowserController.openBookmarkPage(fastView, null, false);
        } else {
            fastView.loadUrl(mHomepage);
        }
    }


    public void activateTab() {
        this.onResume();
        if (this.mTitle != null) {
            this.mTitle.activateTab();
        }
    }

    public boolean canGoBack() {


        if (this.mWebViewList != null && !this.mWebViewList.isEmpty()) {
            WebView nowWebView = this.mWebViewList.get(this.nowId);
            if (nowWebView != null && nowWebView.canGoBack()) {
                return true;
            }
            if (nowWebView == null) {
                return false;
            }
            if (nowWebView.getId() <= 0) {
                return false;
            }

            int v0 = -1;
            int v1 = this.nowId - 1;
            while (v1 >= 0) {
                WebView backWebView = this.mWebViewList.get(v1);
                if (backWebView != null) {
                    if (nowWebView.getProgress() >= 100) {
                        if (backWebView.getUrl() == null) {
                        } else if (backWebView.getTitle() == null) {
                        } else if (backWebView.getUrl().equals(backWebView.getTitle())) {
                        } else if (!backWebView.getTitle().equals("")) {
                            try {
                                String v3 = URLDecoder.decode(backWebView.getTitle(), "utf-8");
                                String v5 = URLDecoder.decode(backWebView.getUrl(), "utf-8");
                                if (nowWebView.getProgress() >= 100) {
                                    if (v3 == null) {
                                    } else if (v5 == null) {
                                    } else if (!v3.equals(v5)) {
                                        String backUrl = backWebView.getUrl();
                                        String nowUrl = nowWebView.getUrl() == null ? "" : nowWebView.getUrl();
                                        if (backUrl.equals(nowUrl)) {
                                        } else {
                                            v0 = v1;
                                            break;
                                        }
                                    }
                                } else {
                                    v0 = v1;
                                    break;
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                    } else {//当前没加载完成
                        try {
                            String v3 = URLDecoder.decode(backWebView.getTitle(), "utf-8");
                            String v5 = URLDecoder.decode(backWebView.getUrl(), "utf-8");
                            if (nowWebView.getProgress() >= 100) {
                                if (v3 == null) {
                                } else if (v5 == null) {
                                } else if (!v3.equals(v5)) {
                                    String backUrl = backWebView.getUrl();
                                    String nowUrl = nowWebView.getUrl() == null ? "" : nowWebView.getUrl();
                                    if (backUrl.equals(nowUrl)) {

                                    } else {
                                        v0 = v1;
                                        break;
                                    }
                                }
                            } else {
                                v0 = v1;
                                break;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                --v1;
            }

            if (v0 != -1 && v0 != this.nowId) {
                return true;
            }

            return false;
        }
        return false;
    }

    public boolean canGoForward() {

        WebView webView = this.mWebViewList.get(this.nowId);
        if (webView != null) {
            if (!this.mIdList.contains(webView.getId() + 1) && !webView.canGoForward()) {
                return false;
            }

            return true;
        }
        return false;
    }

    public void deactivateTab() {
        this.onPause();
        if (this.mTitle != null) {
            this.mTitle.deactivateTab();
        }
    }

    private void destroyWebView(FastView webView) {
        if (webView != null) {
            webView.stopLoading();
            webView.onPause();
            webView.clearHistory();
            webView.setVisibility(View.GONE);
            if (Constants.API <= 19) {
                webView.freeMemory();
            }

            webView.removeAllViews();
            webView.destroyDrawingCache();
            webView.destroy();
        }
    }

    private boolean doDirect(String url) {
        this.loadUrl(url);
        return true;
    }

//    public Bitmap getFavicon() {
//        return this.mTitle.getFavicon();
//    }

    public int getId() {
        int v0 = this.mTitle != null ? this.mTitle.getId() : 0;
        return v0;
    }

    public FrameLayout getMainView() {
        return this.mBrowserFrame;
    }

    public int getProgress() {
        int v0 = this.mWebViewList != null ? this.mWebViewList.get(this.nowId).getProgress() : 100;
        return v0;
    }

    public String getTitle() {
        return this.mTitle.getTitle();
    }

//  public TextView getTitleView() {
//      return this.mTitle.getTitleView();
//  }

    public View getTabView() {
        return this.mTitle.getRootView();
    }

    public String getUrl() {
        String v0 = this.mWebViewList.get(this.nowId) != null ? this.mWebViewList.get(this.nowId).getUrl()
                : "";
        return v0;
    }

    public String getUserAgent() {
        String v0 = this.mWebViewList.get(this.nowId) != null ? this.mWebViewList.get(this.nowId).getSettings()
                .getUserAgentString() : "";
        return v0;
    }

    public int getWebColor() {
        return this.mWebViewList.get(this.nowId).getWebColor();
    }

    public FastView getWebView() {
        return this.mWebViewList.get(this.nowId);
    }

    public void goBack() {
        if (this.mWebViewList != null && !this.mWebViewList.isEmpty()) {
            LogUtils.w(TAG, "go back");
            WebView nowWebView = this.mWebViewList.get(this.nowId);
            if (nowWebView != null && nowWebView.canGoBack()) {
                nowWebView.goBack();
                LogUtils.w(TAG, "go back by system method");
                return;
            }

            if (nowWebView == null) {
                return;
            }

            if (nowWebView.getId() <= 0) {
                return;
            }

            int v0 = -1;
            int v1 = this.nowId - 1;
            while (v1 >= 0) {
                WebView backWebView = this.mWebViewList.get(v1);
                if (backWebView != null) {
                    if (nowWebView.getProgress() < 100) {
                        try {
                            String v3 = URLDecoder.decode(backWebView.getTitle(), "utf-8");
                            String v5 = URLDecoder.decode(backWebView.getUrl(), "utf-8");
                            LogUtils.w(TAG, "now title: " + v3);
                            LogUtils.w(TAG, "now url: " + v5);
                            if (nowWebView.getProgress() < 100) {
                                v0 = v1;
                                break;
                            } else if (v3 == null) {
                            } else if (v5 == null) {
                            } else if (v3.equals(v5)) {
                            } else {
                                String backUrl = backWebView.getUrl();
                                String nowUrl = nowWebView.getUrl() == null ? "" : nowWebView.getUrl();
                                if (backUrl.equals(nowUrl)) {
                                } else {
                                    v0 = v1;
                                    break;
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else if (backWebView.getUrl() == null) {
                    } else if (backWebView.getTitle() == null) {
                    } else if (backWebView.getUrl().equals(backWebView.getTitle())) {
                    } else if (backWebView.getTitle().equals("")) {
                    } else {
                        try {
                            String v3 = URLDecoder.decode(backWebView.getTitle(), "utf-8");
                            String v5 = URLDecoder.decode(backWebView.getUrl(), "utf-8");
                            LogUtils.w(TAG, "now title: " + v3);
                            LogUtils.w(TAG, "now url: " + v5);
                            if (nowWebView.getProgress() < 100) {
                                v0 = v1;
                                break;
                            } else if (v3 == null) {
                            } else if (v5 == null) {
                            } else if (v3.equals(v5)) {
                            } else {
                                String backUrl = backWebView.getUrl();
                                String nowUrl = nowWebView.getUrl() == null ? "" : nowWebView.getUrl();
                                if (backUrl.equals(nowUrl)) {
                                } else {
                                    v0 = v1;
                                    break;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                --v1;
            }

            if (v0 != -1 && v0 != this.nowId) {
                this.nowId = v0;
                this.mBrowserFrame.removeAllViews();
                this.mBrowserFrame.addView(this.mWebViewList.get(this.nowId), this.fraLayoutParams);
                this.initializePreferences(this.mWebViewList.get(this.nowId), this.mActivity);
                this.mBrowserFrame.invalidate();
                this.updateTitle(this.mWebViewList.get(this.nowId));
                LogUtils.w(TAG, "go back by switching web view and set now id = " + String.valueOf(
                        this.nowId));
                this.onPauseOrResume();
            }
        }
    }

    public void goForward() {

        if (this.mWebViewList != null && !this.mWebViewList.isEmpty()) {
            LogUtils.w(TAG, "go forward");
            WebView nowWebView = this.mWebViewList.get(this.nowId);
            if (nowWebView != null && nowWebView.canGoForward()) {
                nowWebView.goForward();
                LogUtils.w(TAG, "go forward by system method");
                return;
            }

            if (nowWebView == null) {
                return;
            }

            if (!this.mIdList.contains(nowWebView.getId() + 1)) {
                return;
            }

            int v0 = -1;
            int v1 = this.nowId + 1;
            while (v1 < this.mWebViewList.size()) {
                WebView backWebView = this.mWebViewList.get(v1);
                if (backWebView != null) {
                    if (nowWebView.getProgress() >= 100) {
                        if (backWebView.getUrl() == null) {
                        } else if (backWebView.getTitle() == null) {
                        } else if (backWebView.getUrl().equals(backWebView.getTitle())) {
                        } else if (!backWebView.getTitle().equals("")) {
                            try {
                                String v3 = URLDecoder.decode(backWebView.getTitle(), "utf-8");
                                String v5 = URLDecoder.decode(backWebView.getUrl(), "utf-8");
                                LogUtils.w(TAG, "now title: " + v3);
                                LogUtils.w(TAG, "now url: " + v5);
                                if (nowWebView.getProgress() >= 100) {
                                    if (v3 == null) {
                                    } else if (v5 == null) {
                                    } else if (v3.equals(v5)) {
                                    } else {
                                        v0 = v1;
                                        break;
                                    }
                                } else {
                                    v0 = v1;
                                    break;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                    } else {
                        try {
                            String v3 = URLDecoder.decode(backWebView.getTitle(), "utf-8");
                            String v5 = URLDecoder.decode(backWebView.getUrl(), "utf-8");
                            LogUtils.w(TAG, "now title: " + v3);
                            LogUtils.w(TAG, "now url: " + v5);
                            if (nowWebView.getProgress() >= 100) {
                                if (v3 == null) {
                                } else if (v5 == null) {
                                } else if (v3.equals(v5)) {
                                } else {
                                    v0 = v1;
                                    break;
                                }
                            } else {
                                v0 = v1;
                                break;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                ++v1;

            }

            if (v0 == -1) {
                return;
            }

            if (v0 == this.nowId) {
                return;
            }

            this.nowId = v0;
            this.mBrowserFrame.removeAllViews();
            this.mBrowserFrame.addView(this.mWebViewList.get(this.nowId), this.fraLayoutParams);
            this.initializePreferences(this.mWebViewList.get(this.nowId), this.mActivity);
            this.nowId = this.mWebViewList.get(this.nowId).getId();
            this.mBrowserFrame.invalidate();
            this.updateTitle(this.mWebViewList.get(this.nowId));
            LogUtils.w(TAG, "go forward by switching web view and set now id = " + String.valueOf(
                    this.nowId));
            this.onPauseOrResume();
        }
    }

    private boolean handleLink(final String url) {
        if (url.contains("mailto:")) {
            MailTo v1 = MailTo.parse(url);
            mActivity.startActivity(IntentUtils.newEmailIntent(mActivity, v1.getTo(), v1.getSubject(),
                    v1.getBody(), v1.getCc()));
            return true;
        }
        if (url.startsWith("folder://")) {
            if (url.substring(9).length() == 0) {
                mBrowserController.openBookmarkPage(mWebViewList.get(nowId), null, true);
            } else {
                mBrowserController.openBookmarkPage(mWebViewList.get(nowId), url.substring(
                        9), true);
            }

            return true;
        }
        if (url.startsWith("history://")) {
            mBrowserController.openHistory();
            return true;
        }

        if (url.startsWith("intent://")) {
            if (!mPreferences.getWebIntentEnabled()) {
                ViewUtils.showToast(mActivity.getResources()
                        .getString(R.string.toast_intent_hint), mActivity);
                return true;
            }

            new SuperActivityToast(mActivity,
                    mActivity.getResources().getString(R.string.msg_intent),
                    mActivity.getResources().getString(R.string.action_ok),
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            try {
                                Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);//1
                                intent.addCategory("android.intent.category.BROWSABLE");
                                intent.setComponent(null);

                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                                    intent.setSelector(null);
                                }

                                mActivity.startActivity(intent);
                            } catch (Exception e) {
                                ViewUtils.showToast(mActivity
                                        .getResources().getString(R.string.toast_operation_failed), mActivity);
                            }
                        }
                    });
            return true;
        }

        if (!url.startsWith("file://") && !url.startsWith("http://") && !url.startsWith("https://")
                && !url.startsWith("ftp://") && !url.startsWith("javascript:") && !url.startsWith(
                "about:") && !url.startsWith("folder://")) {
            if (BrowserView.mPreferences.getWebIntentEnabled()) {
                new SuperActivityToast(mActivity, mActivity.getResources().getString(R.string.msg_intent),
                        mActivity.getResources().getString(R.string.action_ok), new View.OnClickListener() {
                    public void onClick(View view) {
                        LogUtils.w(TAG, "intent look link");
                        if (!mIntentUtils.startActivityForUrl(mWebViewList
                                .get(nowId), url)) {
                            ViewUtils.showToast(mActivity
                                    .getResources().getString(R.string.toast_operation_failed), mActivity);
                        }
                    }
                });
            } else {
                ViewUtils.showToast(mActivity.getResources().getString(R.string.toast_intent_hint), mActivity);
            }

            return true;
        }

        LogUtils.w(TAG, "handle link failed");
        return false;
    }

    @SuppressLint(value = {"SetJavaScriptEnabled", "InlinedApi", "NewApi"})
    public synchronized void initializePreferences(FastView webView, Context context) {

        mHomepage = mPreferences.getHomepage();
        mAdBlock.updatePreference();
        if (this.mSettings == null && webView != null) {
            this.mSettings = webView.getSettings();
        } else if (this.mSettings == null) {
            return;
        }

        switch (BrowserView.mPreferences.getRenderingMode()) {
            case 0: {
                this.mPaint.setColorFilter(null);
                webView.setLayerType(0, this.mPaint);
                break;
            }
            case 1: {
                this.mPaint.setColorFilter(new ColorMatrixColorFilter(BrowserView.mNegativeColorArray));
                webView.setLayerType(2, this.mPaint);
                break;
            }
            case 2: {
                ColorMatrix v0 = new ColorMatrix();
                v0.setSaturation(0f);
                this.mPaint.setColorFilter(new ColorMatrixColorFilter(v0));
                webView.setLayerType(2, this.mPaint);
                break;
            }
            case 3: {
                ColorMatrix v6 = new ColorMatrix();
                v6.set(BrowserView.mNegativeColorArray);
                ColorMatrix v7 = new ColorMatrix();
                v7.setSaturation(0f);
                ColorMatrix v1 = new ColorMatrix();
                v1.setConcat(v6, v7);
                this.mPaint.setColorFilter(new ColorMatrixColorFilter(v1));
                webView.setLayerType(2, this.mPaint);
                break;
            }
        }

        this.mSettings.setGeolocationEnabled(BrowserView.mPreferences.getLocationEnabled());
        if (Constants.API <= 18) {
            switch (BrowserView.mPreferences.getFlashSupport()) {
                case 0: {
                    this.mSettings.setPluginState(WebSettings.PluginState.OFF);
                    break;
                }
                case 1: {
                    this.mSettings.setPluginState(WebSettings.PluginState.ON_DEMAND);
                    break;

                }
                case 2: {
                    this.mSettings.setPluginState(WebSettings.PluginState.ON);
                    break;
                }
            }

        }

        switch (mPreferences.getUserAgentChoice()) {
            case 1: {
                if (Constants.API >= 17) {
                    this.mSettings.setUserAgentString(WebSettings.getDefaultUserAgent(context));
                    break;
                }

                this.mSettings.setUserAgentString(mDefaultUserAgent);
                break;
            }
            case 2: {
                this.mSettings.setUserAgentString("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36");
                break;
            }
            case 3: {
                this.mSettings.setUserAgentString("Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
                break;
            }
            case 4: {
                this.mSettings.setUserAgentString("Mozilla/5.0 (iPhone; CPU iPhone OS 8_0_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12A405 Safari/600.1.4");
                break;
            }
            case 5: {
                this.mSettings.setUserAgentString("Mozilla/5.0 (Symbian/3; Series60/5.2 NokiaN8-00/012.002; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/533.4 (KHTML, like Gecko) NokiaBrowser/7.3.0 Mobile Safari/533.4 3gpp-gba");
                break;
            }
            case 6: {
                this.mSettings.setUserAgentString(BrowserView.mPreferences.getUserAgentString(BrowserView
                        .mDefaultUserAgent));
                break;
            }
        }

        if ((mPreferences.getRuequstDesktopSiteEnabled()) && mPreferences.getUserAgentChoice() != 2
                && mPreferences.getUserAgentChoice() != 3) {
            this.mSettings.setUserAgentString("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36");
        }

        if (Constants.API <= 18) {
            this.mSettings.setSavePassword(BrowserView.mPreferences.getSavePasswordsEnabled());
        }

        this.mSettings.setSaveFormData(BrowserView.mPreferences.getSaveFormDataEnabled());
        this.mSettings.setJavaScriptEnabled(BrowserView.mPreferences.getJavaScriptEnabled());

        mSettings.setJavaScriptCanOpenWindowsAutomatically(!(!BrowserView.mPreferences.getPopupsEnabled() || !BrowserView.mPreferences.getJavaScriptEnabled()));
        if (!BrowserView.mPreferences.getTextReflowEnabled()) {
            this.mSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        } else {
            this.mSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
            if (Constants.API < 19) {
            } else {
                try {
                    this.mSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (!mPreferences.getImageSwitchEnabled()) {//不是智能无图
            mSettings.setBlockNetworkImage(mPreferences.getBlockImagesEnabled());//是否无图
            //设置WebView是否以http、https方式访问从网络加载图片资源,默认false
            mSettings.setLoadsImagesAutomatically(!mPreferences.getBlockImagesEnabled());
            //设置WebView是否加载图片资源，默认true,自动加载图片
        } else if (BrowserUtils.isWifiConnected(context)) {//智能无图 WIFI
            mSettings.setBlockNetworkImage(false);
            mSettings.setLoadsImagesAutomatically(true);
        } else if (BrowserUtils.isDataConnected(context)) {//智能无图 Mobile
            mSettings.setBlockNetworkImage(true);
            mSettings.setLoadsImagesAutomatically(false);
        } else {
            mSettings.setBlockNetworkImage(false);
            mSettings.setLoadsImagesAutomatically(true);
        }

        if ((BrowserUtils.isWifiConnected(context)) || (BrowserUtils.isDataConnected(context))) {
            this.mSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//-1 根据cache-control决定是否从网络上取数据
        } else {
            this.mSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//1
        }

        this.mSettings.setSupportMultipleWindows(BrowserView.mPreferences.getPopupsEnabled());
        this.mSettings.setUseWideViewPort(BrowserView.mPreferences.getUseWideViewportEnabled());
        this.mSettings.setLoadWithOverviewMode(BrowserView.mPreferences.getOverviewModeEnabled());
        switch (mPreferences.getTextSize()) {
            case 1: {
                if (Constants.API >= 14) {
                    this.mSettings.setTextZoom(130);
                    break;
                }

                this.mSettings.setTextSize(WebSettings.TextSize.LARGEST);
                break;
            }
            case 2: {
                if (Constants.API >= 14) {
                    this.mSettings.setTextZoom(115);
                    break;
                }

                this.mSettings.setTextSize(WebSettings.TextSize.LARGER);
                break;
            }
            case 3: {
                if (Constants.API >= 14) {
                    this.mSettings.setTextZoom(100);
                    break;
                }

                this.mSettings.setTextSize(WebSettings.TextSize.NORMAL);
                break;
            }
            case 4: {
                this.mSettings.setTextZoom(85);
                if (Constants.API >= 14) {
                    this.mSettings.setTextZoom(85);
                    break;
                }

                this.mSettings.setTextSize(WebSettings.TextSize.SMALLER);
                break;
            }
            case 5: {
                if (Constants.API >= 14) {
                    this.mSettings.setTextZoom(70);
                    break;
                }

                this.mSettings.setTextSize(WebSettings.TextSize.SMALLEST);
                break;
            }
        }


        switch (mPreferences.getTextEncodingChoice()) {
            case 0: {
                this.mSettings.setDefaultTextEncodingName("UTF-8");
                break;
            }
            case 1: {
                this.mSettings.setDefaultTextEncodingName("GBK");
                break;
            }
            case 2: {
                this.mSettings.setDefaultTextEncodingName("Big5");//大五码（Big5），是通行于台湾、香港地区的一个繁体字编码方案
                break;
            }
            case 3: {
                this.mSettings.setDefaultTextEncodingName("ISO–8859–1");
                break;
            }
            case 4: {
                this.mSettings.setDefaultTextEncodingName("ISO–2022–JP");
                break;
            }
        }


        webView.setDoNotTrack((mPreferences.getDoNotTrackEnabled()) ||
                (mPreferences.getIncognitoModeEnabled()));

        webView.setRemoveIdentifyingHeaders(mPreferences.getRemoveIdentifyingHeadersEnabled() ||
                mPreferences.getIncognitoModeEnabled());

        if (Build.VERSION.SDK_INT < 21) {
            CookieSyncManager.createInstance(context.getApplicationContext());
        }

        CookieManager cookieManager = CookieManager.getInstance();
        if (mPreferences.getIncognitoModeEnabled()) {//无痕模式,禁止Cookie
            cookieManager.setAcceptCookie(mPreferences.getIncognitoCookiesEnabled());
            if (Build.VERSION.SDK_INT >= 21) {
                if (!mPreferences.getIncognitoCookiesEnabled() || mPreferences.getBlock3rdPartyCookiesEnabled()) {
                    cookieManager.setAcceptThirdPartyCookies(webView, false);
                } else {
                    cookieManager.setAcceptThirdPartyCookies(webView, true);
                }
//              cookieManager.setAcceptThirdPartyCookies(webView, !(!mPreferences.getIncognitoCookiesEnabled()
//                        || mPreferences.getBlock3rdPartyCookiesEnabled()));
            }
            return;
        }

        cookieManager.setAcceptCookie(mPreferences.getCookiesEnabled());
        if (Build.VERSION.SDK_INT >= 21) {//5.0同步cookie的操作已经可以自动同步、但前提是我们必须开启第三方cookie的支持。
            if (!mPreferences.getBlock3rdPartyCookiesEnabled()) {
                cookieManager.setAcceptThirdPartyCookies(webView, true);
            } else {
                cookieManager.setAcceptThirdPartyCookies(webView, false);
            }
        }
    }

    @SuppressLint(value = {"SetJavaScriptEnabled", "NewApi", "AddJavascriptInterface"})
    private void initializeSettings(FastView webView, Context context) {
        WebSettings webSettings = webView.getSettings();
        if (Constants.API <= 18) {
            webSettings.setAppCacheMaxSize(Long.MAX_VALUE);//9223372036854775807L
        }

        if (Constants.API <= 17) {
            webSettings.setEnableSmoothTransition(true);
        }

        if (Constants.API >= 17) {
            webSettings.setMediaPlaybackRequiresUserGesture(true);
        }

        if (Constants.API <= 19) {
            webSettings.setDatabasePath(context.getCacheDir() + "/databases");
        }

        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setAppCachePath(context.getCacheDir().toString());
        webSettings.setGeolocationDatabasePath(context.getFilesDir().toString());
        webSettings.setAllowFileAccess(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setAllowContentAccess(true);
        if (Constants.API >= 16) {
            webSettings.setAllowFileAccessFromFileURLs(false);
            webSettings.setAllowUniversalAccessFromFileURLs(false);
        }

        if (Constants.API <= 18) {
            webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        }

        if (Constants.API >= 21) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);//0
        }

        webView.addJavascriptInterface(new JsInteration(), "sweets");
    }

    public synchronized void initializeWebView(Activity activity, FastView webView) {
        webView.setOverScrollMode(View.OVER_SCROLL_NEVER);//2

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            webView.setScrollBarSize(ViewUtils.convertToDensityPixels(this.mBrowserController, 4));
        }


        webView.setDrawingCacheBackgroundColor(0);
        webView.setFocusableInTouchMode(true);
        webView.setFocusable(true);
        webView.setAnimationCacheEnabled(false);
        webView.setDrawingCacheEnabled(true);//设置缓存bitmap,方便截图
        webView.setBackgroundColor(activity.getResources().getColor(android.R.color.white));//17170443

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {//16
            webView.setBackground(null);
            webView.getRootView().setBackground(null);
        } else {
            webView.getRootView().setBackgroundDrawable(null);
        }

        webView.setWillNotCacheDrawing(false);
        webView.setAlwaysDrawnWithCacheEnabled(true);
        webView.setScrollbarFadingEnabled(true);
        webView.setSaveEnabled(true);
        webView.setWebChromeClient(new LightningChromeClient(activity));
        webView.setWebViewClient(new LightningWebClient(activity));
        webView.setDownloadListener(new LightningDownloadListener(activity));
        webView.setOnTouchListener(new OnTouchListener() {
            int mAction;
            int mLocationY;
            int mX;
            int mY;

            @SuppressLint(value = {"ClickableViewAccessibility"})
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                if (view != null && !view.hasFocus()) {
                    view.requestFocus();
                }

                this.mAction = event.getAction();
                this.mY = ((int) event.getY());
                this.mX = ((int) event.getX());
                if (this.mAction == 0) {
                    this.mLocationY = this.mY;
                    mBrowserController.getTouch(this.mX, this.mY);
                } else if (this.mAction == 1) {
                    if ((((int) event.getY())) - this.mLocationY > 50) {
                        mBrowserController.showOperationBar();
                    } else if ((((int) event.getY())) - this.mLocationY < -50) {
                        mBrowserController.hideOperationBar();
                    }

                    this.mLocationY = 0;
                }

                mGestureDetector.onTouchEvent(event);
                return false;
            }
        });
        mDefaultUserAgent = webView.getSettings().getUserAgentString();
        this.mSettings = webView.getSettings();
        this.initializeSettings(webView, activity);
        this.initializePreferences(webView, activity);

    }

    public synchronized void invalidate() {
        if (this.mWebViewList != null) {
            this.mWebViewList.get(this.nowId).invalidate();
        }
    }

    public boolean isDestroyed() {
        return this.isDestroyed;
    }

    public boolean isShown() {
        return this.mBrowserFrame != null && this.mBrowserFrame.isShown();
    }

    @SuppressLint(value = {"NewApi"})
    public synchronized void loadUrl(String url) {
        url = BrowserUtils.changeLink(url);
        if (!this.handleLink(url)) {//处理失败
            if (mPreferences.getQuickBackEnabled() && (url.startsWith("http://") || url.startsWith("https://"))) {
                FastView webview = new FastView(this.mActivity);
                initializeWebView(this.mActivity, webview);//初始化webview
                webview.loadUrl(url);
                if (mIdList.contains(this.nowId + 1)) {
                    for (int i = mIdList.size() - 1; i > this.nowId; --i) {
                        Iterator<FastView> iterator = this.mWebViewList.iterator();
                        while (iterator.hasNext()) {
                            FastView view = iterator.next();
                            if (view.getId() != i) {
                                continue;
                            }

                            this.mWebViewList.remove(view);
                            this.mIdList.remove(i);
                            this.destroyWebView(view);
                        }

                        LogUtils.w(TAG, "destroy webview where id == " + String.valueOf(i));
                    }

                    this.mIdGenerator = this.nowId + 1;
                }

                webview.setId(this.mIdGenerator);
                mIdList.add(this.mIdGenerator);
                LogUtils.w(TAG, "set this page id = " + String.valueOf(this.mIdGenerator));
                nowId = this.mIdGenerator;
                LogUtils.w(TAG, "load url and set now id = " + String.valueOf(this.nowId));
                ++mIdGenerator;
                mWebViewList.add(webview);
                mBrowserFrame.removeAllViews();
                mBrowserFrame.addView(webview, fraLayoutParams);
                LogUtils.w(TAG, "now url: " + url);
            } else if (this.getWebView() == null) {
            } else {
                this.getWebView().loadUrl(url);
                LogUtils.w(TAG, "not control: url");
            }
        }

        this.onPauseOrResume();
    }


    public synchronized void onDestroy() {
        isDestroyed = true;
        if (mWebViewList != null && !mWebViewList.isEmpty()) {
            Iterator<FastView> iterator = this.mWebViewList.iterator();
            while (iterator.hasNext()) {
                FastView fastview = iterator.next();
                if (fastview == null) {
                    continue;
                }

                fastview.stopLoading();
                fastview.onPause();
                fastview.clearHistory();
                fastview.setVisibility(View.GONE);
                if (Build.VERSION.SDK_INT <= 19) {
                    fastview.freeMemory();
                }

                fastview.removeAllViews();
                fastview.destroyDrawingCache();
                fastview.destroy();
            }
        }
        if (mTitle != null) {
            mTitle.onDestroy();
        }
    }

    public synchronized void onPause() {
        Iterator<FastView> iterator = this.mWebViewList.iterator();
        while (iterator.hasNext()) {
            FastView fastv = iterator.next();
            if (this.nowId == fastv.getId()) {
                continue;
            }
            fastv.onPause();
        }
    }

    private void onPauseOrResume() {
        Iterator<FastView> iterator = this.mWebViewList.iterator();
        while (iterator.hasNext()) {
            FastView v0 = iterator.next();
            if (v0 == null) {
                continue;
            }

            if (this.nowId == v0.getId()) {
                v0.onResume();
                continue;
            }

            v0.onPause();
        }
    }

    public synchronized void onResume() {
        Iterator<FastView> iterator = this.mWebViewList.iterator();
        while (iterator.hasNext()) {
            FastView fastView = iterator.next();
            if (this.nowId != fastView.getId()) {
                continue;
            }

            fastView.onResume();
        }
    }

    public synchronized void pauseTimers() {
        if (this.mWebViewList == null) {
        } else {
            this.mWebViewList.get(this.nowId).pauseTimers();
        }
    }

    public void reload() {
        if (this.mWebViewList.get(this.nowId) != null) {
            this.mWebViewList.get(this.nowId).reload();
        }
    }

    public void requestFocus() {
        if (this.mWebViewList != null && !this.mWebViewList.isEmpty() && this.mWebViewList.get(this.nowId)
                != null && (this.mWebViewList.get(this.nowId).hasFocusable()) && !this.mWebViewList
                .get(this.nowId).hasFocus()) {
            this.mWebViewList.get(this.nowId).requestFocus();
        }
    }

    public synchronized void resumeTimers() {
        if (this.mWebViewList != null) {
            this.mWebViewList.get(this.nowId).resumeTimers();
        }
    }

    public void setId(int id) {
        this.mTitle.setId(id);
    }

    public void setInvisible() {
        if (this.mBrowserFrame != null) {
            this.mBrowserFrame.setVisibility(View.INVISIBLE);
        }
    }

    public void setVisibility(int visible) {
        if (this.mBrowserFrame != null) {
            this.mBrowserFrame.setVisibility(visible);
        }
    }

    public void setVisible() {
        if (this.mBrowserFrame != null) {
            this.mBrowserFrame.setVisibility(View.VISIBLE);
            this.mBrowserController.updateUrlBox(this.mWebViewList.get(this.nowId).getUrl(), this.mWebViewList
                    .get(this.nowId).getTitle(), false, false);
        }
    }

    public synchronized void stopLoading() {
        if (this.mWebViewList != null) {
            this.mWebViewList.get(this.nowId).stopLoading();
        }
    }

    private void updateTitle(FastView webView) {
        if (webView != null) {
            String title = webView.getTitle() == null ? this.mActivity.getString(R.string.untitled) : webView.getTitle();
            mTitle.setTitle(title);
//            Bitmap icon = webView.getFavicon() == null ? BitmapFactory.decodeResource(this.mActivity.getResources(),
//                    R.drawable.ic_webpage) : webView.getFavicon();
//            mTitle.setFavicon(icon);

            if (!this.mBrowserFrame.isShown()) {
                return;
            }
            if (this.nowId != webView.getId()) {
                return;
            }

            LogUtils.w(TAG, "reach update url box");
            mBrowserController.updateUrlBox(webView.getUrl(), title, false, false);
            mBrowserController.updateProgress(webView.getProgress());
            mBrowserController.updateColor(webView.getWebColor());
        }
    }
}

